package com.sky.utils;



import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sky.exception.OrderBusinessException;
import com.sky.properties.ShopProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;


@Component
@Slf4j
public class BaiduMapUtil {
    //自己的ak码
    public static final String myAk= "uTfyj8p73xHssIncHGNqkOe1u9wDrvWb";

    /**
     * 根据地址获取经纬度
     * @param address
     * @return 第一个值为lng，第二个值为lat
     */
    public String getLngAndLatByAddressName(String address) throws IOException {

        //支付宝获取商家或用户的经纬度地址
        String url = "https://api.map.baidu.com/geocoding/v3/";
        //创建一个map集合
        Map map = new HashMap();
        map.put("address",address);
        map.put("ak",myAk);
        map.put("output","json");
        String doGet = HttpClientUtil.doGet(url, map);

        JSONObject jsonObject = JSONObject.parseObject(doGet);
        log.info("输出是:{}",jsonObject);

        if (!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("经纬度解析错误");
        }

        JSONObject result = jsonObject.getJSONObject("result");
        JSONObject location = result.getJSONObject("location");
        //纬度值
        Double lat = location.getDouble("lat");
        //纬度值
        Double lng = location.getDouble("lng");

        StringBuilder sb =  new StringBuilder();
        //商家的经纬度
        String string = sb.append(lat).append(",").append(lng).toString();

        return string;
    }

    public Long getadderss(String geographical,String userGeographical) {
        String url = "https://api.map.baidu.com/directionlite/v1/driving";

        Map map = new HashMap();

        map.put("origin", geographical);
        map.put("ak", myAk);
        map.put("output", "json");
        map.put("destination", userGeographical);

        String doGet = HttpClientUtil.doGet(url, map);

        JSONObject jsonObject = JSONObject.parseObject(doGet);

        if (!jsonObject.getString("status").equals("0")) {
            throw new OrderBusinessException("666错误");
        }

        JSONObject result = jsonObject.getJSONObject("result");

        JSONArray routes = (JSONArray) result.get("routes");

        JSONObject o = (JSONObject) routes.get(0);
        Long distance = o.getLong("distance");

        if (distance > 5000) {
            throw new OrderBusinessException("配送超过范围");
        }

        return distance;

    }
}